using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using GomokuGame.AI;

namespace GomokuGame
{
    /// <summary>
    /// 游戏记录类，用于保存和加载游戏对局
    /// </summary>
    [Serializable]
    public class GameRecord
    {
        /// <summary>
        /// 对局基本信息
        /// </summary>
        public GameInfo GameInfo { get; set; }
        
        /// <summary>
        /// 移动历史记录
        /// </summary>
        public List<MoveRecord> Moves { get; set; }
        
        /// <summary>
        /// 游戏结果
        /// </summary>
        public GameResult Result { get; set; }
        
        public GameRecord()
        {
            GameInfo = new GameInfo();
            Moves = new List<MoveRecord>();
            Result = new GameResult();
        }
        
        /// <summary>
        /// 添加移动记录
        /// </summary>
        public void AddMove(int row, int col, PieceType pieceType, TimeSpan timestamp)
        {
            Moves.Add(new MoveRecord
            {
                Row = row,
                Col = col,
                PieceType = pieceType,
                Timestamp = timestamp,
                MoveNumber = Moves.Count + 1
            });
        }
        
        /// <summary>
        /// 保存到XML文件
        /// </summary>
        public void SaveToXml(string filePath)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(GameRecord));
                using (var writer = new StreamWriter(filePath, false, Encoding.UTF8))
                {
                    serializer.Serialize(writer, this);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"保存游戏记录失败: {ex.Message}", ex);
            }
        }
        
        /// <summary>
        /// 从XML文件加载
        /// </summary>
        public static GameRecord LoadFromXml(string filePath)
        {
            try
            {
                var serializer = new XmlSerializer(typeof(GameRecord));
                using (var reader = new StreamReader(filePath, Encoding.UTF8))
                {
                    return (GameRecord)serializer.Deserialize(reader);
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"加载游戏记录失败: {ex.Message}", ex);
            }
        }
        
        /// <summary>
        /// 导出为SGF格式
        /// </summary>
        public string ExportToSGF()
        {
            var sgf = new StringBuilder();
            
            // SGF头部信息
            sgf.AppendLine("(;");
            sgf.AppendLine($"FF[4]");
            sgf.AppendLine($"GM[15]");
            sgf.AppendLine($"SZ[15]");
            sgf.AppendLine($"DT[{GameInfo.StartTime:yyyy-MM-dd HH:mm:ss}]");
            sgf.AppendLine($"PB[{GameInfo.BlackPlayer}]");
            sgf.AppendLine($"PW[{GameInfo.WhitePlayer}]");
            sgf.AppendLine($"RU[Chinese]");
            
            // 添加移动记录
            foreach (var move in Moves)
            {
                var color = move.PieceType == PieceType.Black ? "B" : "W";
                var position = ConvertToSGFPosition(move.Row, move.Col);
                sgf.AppendLine($";{color}[{position}]");
            }
            
            // 游戏结果
            if (Result.Winner != PieceType.Empty)
            {
                var winner = Result.Winner == PieceType.Black ? "B" : "W";
                sgf.AppendLine($"RE[{winner}+{Result.WinReason}]");
            }
            else if (Result.IsDraw)
            {
                sgf.AppendLine("RE[Draw]");
            }
            
            sgf.AppendLine(")");
            
            return sgf.ToString();
        }
        
        /// <summary>
        /// 将棋盘坐标转换为SGF格式坐标
        /// </summary>
        private string ConvertToSGFPosition(int row, int col)
        {
            // SGF使用字母坐标，a-o表示0-14
            var colChar = (char)('a' + col);
            var rowChar = (char)('a' + row);
            return $"{colChar}{rowChar}";
        }
    }
    
    /// <summary>
    /// 游戏基本信息
    /// </summary>
    [Serializable]
    public class GameInfo
    {
        /// <summary>
        /// 游戏开始时间
        /// </summary>
        public DateTime StartTime { get; set; }
        
        /// <summary>
        /// 游戏结束时间
        /// </summary>
        public DateTime EndTime { get; set; }
        
        /// <summary>
        /// 游戏模式
        /// </summary>
        public GameMode GameMode { get; set; }
        
        /// <summary>
        /// 黑方玩家名称
        /// </summary>
        public string BlackPlayer { get; set; }
        
        /// <summary>
        /// 白方玩家名称
        /// </summary>
        public string WhitePlayer { get; set; }
        
        /// <summary>
        /// AI难度（如果适用）
        /// </summary>
        public AIDifficulty? AIDifficulty { get; set; }
        
        /// <summary>
        /// AI执子颜色（如果适用）
        /// </summary>
        public PieceType? AIPlayer { get; set; }
        
        public GameInfo()
        {
            StartTime = DateTime.Now;
            BlackPlayer = "黑方";
            WhitePlayer = "白方";
        }
    }
    
    /// <summary>
    /// 移动记录
    /// </summary>
    [Serializable]
    public class MoveRecord
    {
        /// <summary>
        /// 行坐标
        /// </summary>
        public int Row { get; set; }
        
        /// <summary>
        /// 列坐标
        /// </summary>
        public int Col { get; set; }
        
        /// <summary>
        /// 棋子类型
        /// </summary>
        public PieceType PieceType { get; set; }
        
        /// <summary>
        /// 时间戳
        /// </summary>
        public TimeSpan Timestamp { get; set; }
        
        /// <summary>
        /// 移动序号
        /// </summary>
        public int MoveNumber { get; set; }
    }
    
    /// <summary>
    /// 游戏结果
    /// </summary>
    [Serializable]
    public class GameResult
    {
        /// <summary>
        /// 获胜方
        /// </summary>
        public PieceType Winner { get; set; }
        
        /// <summary>
        /// 获胜原因
        /// </summary>
        public string WinReason { get; set; }
        
        /// <summary>
        /// 是否平局
        /// </summary>
        public bool IsDraw { get; set; }
        
        /// <summary>
        /// 总移动数
        /// </summary>
        public int TotalMoves { get; set; }
        
        /// <summary>
        /// 游戏时长
        /// </summary>
        public TimeSpan Duration { get; set; }
        
        public GameResult()
        {
            Winner = PieceType.Empty;
            WinReason = "";
            IsDraw = false;
        }
    }
} 